package com.world.rickcloudendpoint.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.world.rickcloudendpoint.demo.QueueConstantKey;
import com.world.rickcloudendpoint.demo.RedisService;
import com.world.rickcloudendpoint.demo.redis.RedisMqConsumerContainer;
import com.world.rickcloudendpoint.demo.QueueConfig;
import com.world.rickcloudendpoint.demo.redis.consumer.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @description: redis 配置
 * @author: jlsong
 * @date: 2021/12/14 23:08:34
 * @version: 1.0
 */
@Configuration
@EnableCaching
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.database}")
    private Integer database;

    @Value("${spring.redis.port}")
    private Integer port;

    @Value("${spring.redis.password}")
    private String pwd;


    @Primary
    @Bean(name = "jedisPoolConfig")
    @ConfigurationProperties(prefix = "spring.redis.pool")
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        return jedisPoolConfig;
    }


    @Bean
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setDatabase(database);
        redisStandaloneConfiguration.setPassword(pwd);
        redisStandaloneConfiguration.setPort(port);
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
        jpcb.poolConfig(jedisPoolConfig);
        JedisClientConfiguration jedisClientConfiguration = jpcb.build();
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }

    /**
     * 配置redisTemplate，针对不同key和value场景下不同序列化的方式
     *
     * @param factory redis连接工厂
     * @return
     */
    @Primary
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer redisSerializer = new Jackson2JsonRedisSerializer(Object.class); // object序列化成json字符串

        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        redisSerializer.setObjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // 字符串序列化
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);

        // value序列化方式采用jackson
        template.setValueSerializer(redisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(redisSerializer);
        template.afterPropertiesSet();
        return template;
    }


    @Bean
    @SuppressWarnings("unchecked")
    public RedisScript<Long> limitRedisScript() {
        DefaultRedisScript redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/redis/limit.lua")));
        redisScript.setResultType(Long.class);
        return redisScript;
    }


    @Bean(initMethod = "init", destroyMethod = "destroy")
    public RedisMqConsumerContainer redisMqConsumerContainer(@Autowired RedisService redisService,
                                                             OneConsumer one,
                                                             TwoConsumer two,
                                                             ThreeConsumer three,
                                                             FourConsumer four,
                                                             FiveConsumer five,
                                                             SixConsumer six,
                                                             SevenConsumer seven,
                                                             EightConsumer eight) {
        RedisMqConsumerContainer container = new RedisMqConsumerContainer(redisService);
        String keyPrefix = QueueConstantKey.CACHE_PREFIX.concat(":");

        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_ONE).consumer(one).build());
        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_TWO).consumer(two).build());
        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_THREE).consumer(three).build());
        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_FOUR).consumer(four).build());
        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_FIVE).consumer(five).build());
        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_SIX).consumer(six).build());
        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_SEVEN).consumer(seven).build());
        container.addConsumer(QueueConfig.builder().queue(keyPrefix + QueueConstantKey.RECEIVE_EIGHT).consumer(eight).build());
        return container;
    }

}
